package handler

import (
	"encoding/json"
	"filestore-server/meta"
	"filestore-server/util"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)
func UploadHandler(w http.ResponseWriter,r *http.Request){
	if r.Method=="GET"{
		//返回上传html页面
		data,err := os.ReadFile("./static/view/index.html")
		if err!=nil{
			io.WriteString(w,"internel server error")
			return
		}
		io.WriteString(w,string(data))
	}else if r.Method=="POST"{
		//接收文件流及存储到本地目录
		file,head,err := r.FormFile("file")
		if err != nil{
			fmt.Printf("Failed to get data,err:%s\n",err.Error())
			return
		}
		defer file.Close()
		fileMeta := meta.FileMeta{
			FileName:head.Filename,
			Location:"/tmp/"+head.Filename,
			UploadAt: time.Now().Format("2006-01-02 15:04:05"),
		}
		newFile,err := os.Create(fileMeta.Location)
		if err != nil{
			fmt.Printf("Failed to create file,err:%s\n",err.Error())
			return 
		}
		defer newFile.Close()
		fileMeta.FileSize,err = io.Copy(newFile,file)
		if err !=nil{
			fmt.Printf("Failed to save data into file,err:%s\n",err.Error())
			return 
		}
		newFile.Seek(0,0)//文件读写指针移到开头
		fileMeta.FileSha1=util.FileSha1(newFile)
		_=meta.UpdateFileMetaDB(fileMeta)
		http.Redirect(w,r,"/file/upload/suc",http.StatusFound)

	}
}

//UploadSucHandler:上传已完成
func UploadSucHandler(w http.ResponseWriter,r *http.Request){
	io.WriteString(w,"Upload finished!")
}
//GetFileMetaHandler：获取文件元信息
func GetFileMetaHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	filehash := r.Form["filehash"][0]
	fmeta,ok := meta.GetFileMetaDB(filehash)
	if ok != nil {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	data,err := json.Marshal(fmeta)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(data)
}
func DownloadHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	fsha1 := r.Form.Get("filehash")
	fm,ok := meta.GetFileMeta(fsha1)
	if !ok {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	f,err := os.Open(fm.Location)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer f.Close()
	data,err := io.ReadAll(f)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type","application/octect-stream")
	w.Header().Set("Content-Description","attachment;filename=\""+fm.FileName+"\"")
	w.Write(data)

}

//filemetaupdatehandle:更新元信息接口（重命名）
func FileMetaUpdateHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	filesha1 := r.Form.Get("filehash")
	newFileName := r.Form.Get("filename")
	opType := r.Form.Get("op")
	if opType != "0"{
		w.WriteHeader(http.StatusForbidden)
		return
	}
	if r.Method != "POST"{
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	curFileMeta,ok := meta.GetFileMeta(filesha1)
	if !ok {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	curFileMeta.FileName = newFileName
	meta.UpdateFileMeta(curFileMeta)
	w.WriteHeader(http.StatusOK)
	data,err := json.Marshal(curFileMeta)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write(data)
}
//FileMetaDeleteHandler:删除文件元信息
func FileMetaDeleteHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	filesha1 := r.Form.Get("filehash")
	fMeta,ok := meta.GetFileMeta(filesha1)
	if !ok {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	os.Remove(fMeta.Location)//可能会失败，但是我们不管
	meta.RemoveFileMeta(filesha1)
	w.WriteHeader(http.StatusOK)

}